package com.starblink.product.detail.adapter.view

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.VibrateUtils
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.guide.SkNoviceManage
import com.starblink.android.basic.guide.bean.SkGuideEnum
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.FontUtil
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.widget.flowlayout.FlowLayout
import com.starblink.android.basic.widget.flowlayout.TagAdapter
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.ext.contentViewHeight2
import com.starblink.basic.style.view.indicator.GuangDrawableIndicator
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.novice_guide.product.ProductFindSimilarPopViewV2
import com.starblink.library.widget.product.pop.GoodsFindSimilarPop
import com.starblink.library.widget.wishlist.WishlistAddBottomDialog
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.product.R
import com.starblink.product.databinding.ItemProductDetailCardBinding
import com.starblink.product.detail.adapter.ProductImgAdapter
import com.starblink.product.detail.dialog.ProductReviewsDialog
import com.starblink.rocketreserver.fragment.ProductD
import com.youth.banner.listener.OnPageChangeListener

class ProductDetailCardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleRes: Int = 0
) : ConstraintLayout(context, attrs, defStyleRes) {

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
    }

    private val collectImg = R.mipmap.icon_detail_collect
    private val collectedImg = R.mipmap.icon_detail_collected

    val viewBinding: ItemProductDetailCardBinding =
        ItemProductDetailCardBinding.inflate(inflater, this, true)

    var isSimpleDialog: Boolean = false//是否是商品挂载弹窗
    var hasNext: Boolean = true//前三个引导页是否有下一个
    var showGuide: Boolean = false//展示引导框

    var index: Int = 0
    var traceId: String = ""
    var firstTraceInfo: String? = ""
    var pageTrackTag: String = ""
    var currentImgUrl: String? = ""//当前展示图片 用于识图
    var hasShowed: Boolean = false//是否已初始化过

    lateinit var product: ProductD

    var dialog: Dialog? = null
    var pageDef: Int = SpmPageDef.SimilarProductListPage
    private var turnWeb: (() -> Unit)? = null

    fun bindPost(
        activity: FragmentActivity,
        product: ProductD,
        position: Int,
        traceId: String = "",
        isSimpleDialog: Boolean = false,
        isFromFeeds: Boolean = false,
        hasNext: Boolean = true,
        showGuide: Boolean = false,
        pageTrackTag: String,
        turnWeb: (() -> Unit)? = null
    ) {
        this.isSimpleDialog = isSimpleDialog
        this.hasNext = hasNext
        this.turnWeb = turnWeb
        this.showGuide = showGuide
        this.product = product
        this.pageTrackTag = pageTrackTag
        this.traceId = traceId
        currentImgUrl = product.mainImg
        index = position

        setListener(activity)
        setView(activity)

        if (!hasShowed) {
            if (position == 0 && isFromFeeds) {
                firstTraceInfo = product.traceInfo
                viewBinding.bgBanner.visibleOrGone(false) {}
            }
        } else {
            viewBinding.bgBanner.visibleOrGone(true) {}
        }

        if (position == 0) {
            if (!hasShowed) {
                hasShowed = true
                Log.e("ProductDetailCardView", "=====$index=")
                trackData(
                    page = pageDef,
                    element = SpmElementDef.ProductDetailNewBody,
                    traceInfo = traceInfo(),
                    showRatio = 0.9f,
                    params = trackMap(),
                    businessSuffixID = businessSuffixId(product)
                )
            }
        } else {
            Log.e("ProductDetailCardView", "=====$index=")
            trackData(
                page = pageDef,
                element = SpmElementDef.ProductDetailNewBody,
                traceInfo = traceInfo(),
                showRatio = 0.9f,
                params = trackMap(),
                businessSuffixID = businessSuffixId(product)
            )
        }
    }

    private fun setView(
        activity: FragmentActivity,
    ) {
        updateCollect(product.collected)
        if (product.hotBrand != null && product.hotBrand!!.name?.isNotEmpty() == true) {
            viewBinding.hotBrand.visibleOrGone(true) {}
            viewBinding.hotBrand.text = product.hotBrand!!.name
//            viewBinding.tvName.text = "${product.hotBrand!!.name} | ${product.title}"
        } else {
            viewBinding.hotBrand.visibleOrGone(false) {}
//            viewBinding.tvName.text = product.title
        }
        viewBinding.tvName.text = product.title
        product.price?.let {
            viewBinding.tvPrice.show(
                it,
                product.currency,
                product.currencySymbol
            )
        }

//        product.selectedListLabel?.let {
        setSelectedListLabel()
//        }

//        setReviewView(activity, product.reviewTotal, product.grade)
        setMoreInfoView()

        setStoreView()
        setDiscountInfoView()

        setImageBanner(index, activity)
    }

    private fun trackMap(
    ) = SpmTrackHandler.trackProductMap(index, product, traceId = traceId)

    //设置商品折扣信息、bestseller标签
    private fun setDiscountInfoView() {
        val disCountInfo = product.disCountInfo
        val cornerLabels = product.cornerLabels
        viewBinding.tvBestTag.visibleOrGone(false) {}
        viewBinding.tvPriceDiscount.visibleOrGone(false) {}
        viewBinding.tvPrice.setPriceColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_text_primary))

//        var disCountInfo = ProductD.DisCountInfo(discountPercent = "40", underlinePrice = Double.parseDouble("10"), discountText = "100")
        if (disCountInfo != null) {
//            Log.e("ProductDetailCardView", "=====000000000==$disCountInfo")
//            viewBinding.tvDiscount.visibleOrGone(disCountInfo.discountText?.isNotEmpty() == true) {
//                viewBinding.tvDiscount.text = "${disCountInfo.discountText}"
//            }

            viewBinding.tvPriceDiscount.visibleOrGone(disCountInfo.discountText?.isNotEmpty() == true && disCountInfo.underlinePrice != null) {
                disCountInfo.underlinePrice?.let {
                    viewBinding.tvPriceDiscount.show(
                        it,
                        product.currency,
                        product.currencySymbol
                    )
                }
                viewBinding.tvPrice.setPriceColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_brand_600))
            }

        }
//        if (!viewBinding.tvDiscount.isVisible && cornerLabels?.isNotEmpty() == true) {
//            //显示trending标
//            viewBinding.tvBestTag.setBackgroundResource(R.drawable.bg_btn_trending)
//            val type = cornerLabels.first().type
//            viewBinding.tvBestTag.visibleOrGone(type == 1 || type == 2 || type == 3 || type == 4) {
//                viewBinding.tvBestTag.text = cornerLabels.first().title
//                if (type == 3) {
//                    viewBinding.tvBestTag.setBackgroundResource(R.drawable.bg_btn_bestsaller)
//                }
//            }
//        }
    }

    //设置商品更多信息、标签
    private fun setMoreInfoView() {
        viewBinding.tvFreeShop.visibleOrGone(false) {}
//        viewBinding.llTags.visibleOrGone(false) {}
        viewBinding.ivMoreInfo.visibleOrGone(false) {}
        viewBinding.ivKlarnaPay.visibleOrGone(false) {}
        viewBinding.llInfo.visibleOrGone(false) {}

        if (!isSimpleDialog) {
            if (product.logistics != null || product.paymentWay?.isNotEmpty() == true) {
//                if (product.logistics?.deliveryTime != null || product.paymentWay?.isNotEmpty() == true) {
//                    viewBinding.ivMoreInfo.visibleOrGone(true) {}
//                }
                viewBinding.llInfo.visibleOrGone(true) {
                    viewBinding.ivKlarnaPay.visibleOrGone(product.klarnaPayFlag == true) {}
//                    viewBinding.ivMoreInfo.visibleOrGone(product.klarnaPayFlag == true && product.paymentWay?.isNotEmpty() == true) {}
                    viewBinding.divideShipping.visibleOrGone(product.logistics?.deliveryTime != null && product.klarnaPayFlag == true) {}
                    viewBinding.tvShippingTime.visibleOrGone(product.logistics?.deliveryTime != null) {
                        val minDays =
                            if (product.logistics?.deliveryTime == null) 0 else product.logistics?.deliveryTime!!.minDays
                        val maxDays =
                            if (product.logistics?.deliveryTime == null) 0 else product.logistics?.deliveryTime!!.maxDays
                        if (minDays == maxDays) {
                            viewBinding.tvShippingTime.text =
                                "Usually shipping within $minDays days"
                        } else {
                            viewBinding.tvShippingTime.text =
                                "Usually shipping within $minDays - $maxDays days"
                        }
                    }
                }
            } else {
//                showFrontList()
            }
            if (product.logistics?.shippingTag?.isNotEmpty() == true) {
                viewBinding.tvFreeShop.visibleOrGone(true) {}
                viewBinding.tvFreeShop.text = product.logistics!!.shippingTag
            } else {
//                        if (product.klarnaPayFlag != true) {//只有无klarna标签和物流方式时展示
//                            viewBinding.tvFreeShop.visibleOrGone(true) {}
//                            viewBinding.tvFreeShop.text =
//                                CommUtils.getString(com.starblink.basic.style.R.string.Payment_Information)
//                        }
            }
        } else {//弹窗不考虑物流信息优先级逻辑
//            showFrontList()
        }
        if (viewBinding.llInfo.isVisible) {
            viewBinding.tvName.maxLines = 2
        } else {
            viewBinding.tvName.maxLines = 3
        }
    }

    private fun showFrontList() {

        var frontPropertyList = product.frontPropertyList
        if (frontPropertyList?.isNotEmpty() == true) {
            if ((frontPropertyList.size == 1 && frontPropertyList.first().value == "bestseller")) {
                return
            }
            if (frontPropertyList.first().value == "bestseller" && frontPropertyList.size > 1) {
                frontPropertyList = frontPropertyList.subList(1, frontPropertyList.size)
            }
            if (frontPropertyList.size > 3) {
                frontPropertyList = frontPropertyList.subList(0, 3)
            }
            if (frontPropertyList.isNotEmpty()) {
                viewBinding.llTags.visibleOrGone(true) {}
                viewBinding.llInfo.visibleOrGone(false) {}
                viewBinding.flTags.adapter =
                    object : TagAdapter<ProductD.FrontPropertyList>(frontPropertyList) {
                        override fun getView(
                            parent: FlowLayout?,
                            position: Int,
                            s: ProductD.FrontPropertyList
                        ): View {
                            val tv: TextView = inflate(
                                context,
                                R.layout.item_front_property,
                                null
                            ) as TextView
                            if (s != null) {
                                tv.text = s.value
                            }
                            return tv
                        }
                    }
                viewBinding.flTags.setMaxLine(1)
            }
        }
    }

    //设置分数评分
    private fun setReviewView(activity: FragmentActivity, reviewTotal: String?, grade: Int? = 0) {
        viewBinding.llScore.visibleOrGone(grade ?: 0 >= 4) {
            viewBinding.ivScore5.setImageResource(if (grade ?: 0 > 4) R.mipmap.icon_good_score else R.mipmap.icon_good_score_empty)
        }
        viewBinding.tvCommentNum.visibleOrGone(false) {}
        if (!isSimpleDialog) {
            viewBinding.tvCommentNum.visibleOrGone(reviewTotal?.isNotEmpty() == true && reviewTotal != "0") {
                viewBinding.tvCommentNum.text = "($reviewTotal)"

                viewBinding.llReview.run {
                    trackData(
                        page = pageDef,
                        element = SpmElementDef.ProductDetailNewBody,
                        traceInfo = traceInfo(),
                        params = trackMap(), onlyHit = true
                    )
                    click {
                        product.standardSpuIds?.let { it1 ->
                            ProductReviewsDialog(
                                activity, it1,
                            ) {
                                toLink(product)
                            }.show(activity.supportFragmentManager, "review")
                        }
                    }
                }
            }
        }
    }

    //设置榜单信息
    private fun setSelectedListLabel(
    ) {
        viewBinding.llNewIn.visibleOrGone(false) {}
        val layoutParam: LayoutParams = viewBinding.llContent.layoutParams as LayoutParams

        if (product.disCountInfo != null && product.disCountInfo?.discountPercent?.isNotEmpty() == true) {
            viewBinding.llNewIn.visibleOrGone(true) {
                viewBinding.tvNewIn.buildSpannableString {
                    addText("Buy with ") {
                        setColor(Color.parseColor("#29292A"))
                        FontUtil.getTypeface(FontUtil.MONTSERRAT_SEMIBOLD)?.let {
                            setTypeface(it)
                        }
                    }
                    addText(product.disCountInfo?.discountPercent ?: "") {
                        setColor(Color.parseColor("#D62F51"))
                        setScale(1.15f)
                        FontUtil.getTypeface(FontUtil.MONTSERRAT_BOLD)?.let {
                            setTypeface(it)
                        }
                    }
                    addText(" off") {
                        setColor(Color.parseColor("#29292A"))
                        FontUtil.getTypeface(FontUtil.MONTSERRAT_SEMIBOLD)?.let {
                            setTypeface(it)
                        }
                    }

                }
                layoutParam.topMargin = dp2px(-32f)

                (viewBinding.ivImgSearch.layoutParams as LayoutParams).bottomMargin = 53.dp
                (viewBinding.tvBestTag.layoutParams as LayoutParams).bottomMargin = 53.dp
                (viewBinding.addBoard.layoutParams as LayoutParams).bottomMargin = 50.dp
            }
        } else {
            layoutParam.topMargin = dp2px(-30f)
            viewBinding.llNewIn.visibleOrGone(false) {}
            (viewBinding.ivImgSearch.layoutParams as LayoutParams).bottomMargin = 16.dp
            (viewBinding.addBoard.layoutParams as LayoutParams).bottomMargin = 4.dp
        }

    }

    //设置底部店铺view
    private fun setStoreView() {
        val merchantWebVOF = product.merchantWeb
        viewBinding.ivStore.load(merchantWebVOF?.logo, merchantWebVOF?.merchantName)
        viewBinding.tvStoreName.text = merchantWebVOF?.merchantName ?: ""
        merchantWebVOF?.let { updateFollow(it.subOrNot) }
    }

    /**
     * 设置图片区域
     */
    @SuppressLint("MissingPermission")
    private fun setImageBanner(
        position: Int,
        activity: FragmentActivity,
    ) {
        val lp: LayoutParams = viewBinding.divide2.layoutParams as LayoutParams
        lp.height = 10.dp

        var imgContainerH = activity.contentViewHeight2 - dp2px(210f + 10f - 30f)
        if (viewBinding.llNewIn.isVisible) {
            imgContainerH -= 36.dp
        }
        val lpBg: LayoutParams = viewBinding.bgBanner.layoutParams as LayoutParams
        lpBg.height = 300.dp

        if (!isSimpleDialog) {
            if (index < 3 && hasNext) {
                imgContainerH -= dp2px(78f)//存在引导
                lpBg.height = 250.dp
                lp.height = 24.dp

                viewBinding.container.updateLayoutParams {
                    width = ViewGroup.LayoutParams.MATCH_PARENT
                    height = ViewGroup.LayoutParams.WRAP_CONTENT
                }
            } else {
                viewBinding.container.updateLayoutParams {
                    width = ViewGroup.LayoutParams.MATCH_PARENT
                    height = ViewGroup.LayoutParams.MATCH_PARENT
                }
            }
        } else {
            viewBinding.bgBanner.visibleOrGone(false) {}
            viewBinding.bgTop.visibleOrGone(false) {}
            imgContainerH -= 44.dp//挂载商品弹窗

            viewBinding.container.updateLayoutParams {
                width = ViewGroup.LayoutParams.MATCH_PARENT
                height = ViewGroup.LayoutParams.WRAP_CONTENT
            }
        }
        viewBinding.divide2.layoutParams = lp
        viewBinding.banner.updateLayoutParams {
            width = ViewGroup.LayoutParams.MATCH_PARENT
            height = imgContainerH
        }

        if (product.allImageUrlList?.size ?: 0 > 1) {//预加载轮播后续图片
            for (i in product.allImageUrlList?.indices!!) {
                if (i > 0) {
                    val item = product.allImageUrlList!![i]
                    ImageUtils.preloadImage(commContext(), item)
                }
            }
        }

//        if (!hasShowed) {
        viewBinding.banner.run {
            this//添加生命周期观察者
                .setAdapter(
                    ProductImgAdapter(
                        product.allImageUrlList ?: listOf(),
                        context,
                        product.mainPicSize,
                        imgContainerH, itemIndex = index,
                        longClickCall = {
                            if (currentImgUrl.isNullOrEmpty() || product.id.isNullOrEmpty()) {
                                false
                            } else {
                                VibrateUtils.vibrate(100L)

                                val pop = if (dialog != null) {
                                    GoodsFindSimilarPop(dialog!!) {
                                        collect(activity, product)
                                    }
                                } else {
                                    GoodsFindSimilarPop(context) {
                                        collect(activity, product)
                                    }
                                }
                                pop.showPopup(
                                    it,
                                    currentImgUrl!!,
                                    product.id!!,
                                    product.type,
                                    add = product.collected == true
                                )
                                pop.track(
                                    pageDef,
                                    trackMap(),
                                    traceInfo = traceInfo() ?: "",
                                )
                                SpmTrackHandler.addSingleTrackData(
                                    SkAntEntity(
                                        event = TrackEvent.elementClick.value,
                                        traceInfo = traceInfo() ?: "",
                                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                                            pageDef,
                                            SpmElementDef.GOODS_CARD_FIND_SIMILAR
                                        ),
                                        params = trackMap()
                                    )
                                )
                                true
                            }
                        }
                    ) {
                        toLink(product)
                        SpmTrackHandler.addSingleTrackData(
                            SkAntEntity(
                                event = TrackEvent.elementClick.value,
                                traceInfo = traceInfo() ?: "",
                                spmCnt = GTrackerAssistUtils.fetchElementValue(
                                    pageDef,
                                    SpmElementDef.ProductDetailNewBody
                                ),
                                params = trackMap()
                            )
                        )
                    }
                ).setLoopTime(4000)
                .isAutoLoop(true)
//                .isAutoLoop(index == 0)
                .addOnPageChangeListener(object : OnPageChangeListener {
                    override fun onPageScrolled(
                        position: Int,
                        positionOffset: Float,
                        positionOffsetPixels: Int
                    ) {
                    }

                    override fun onPageSelected(position: Int) {
//                            if(product.allImageUrlList?.size ?: 0 > position) {
                        currentImgUrl =
                            product.allImageUrlList?.get(position) ?: product.mainImg
//                            }
                    }

                    override fun onPageScrollStateChanged(state: Int) {
                    }
                })
                .setIndicatorSpace(dp2px(6f))
                .setIndicator(
                    GuangDrawableIndicator(
                        activity,
                    )
                )
//            }
        }
        if (SkNoviceManage.canShowGuide(
                SkGuideEnum.HOME_FRG_1_PRODUCT_COLL_V2
            ) && position == 0
        ) {
            viewBinding.bannerLay.postDelayed({
                ProductFindSimilarPopViewV2.pushPopWindow(
                    viewBinding.bannerLay,
                    viewBinding.root,
                    dismissCallBack = {
                        SkNoviceManage.hasPopGuide(SkGuideEnum.HOME_FRG_1_PRODUCT_COLL_V2)
                    }
                )
            }, 500)

        }
    }

    private fun toLink(product: ProductD) {
        product.id?.let { it1 ->
            CommonRoute.startProductLink(
                context,
                product.url,
                it1, productId = product.productId ?: "", product.standardSpuIds ?: "",
                product.collected == true,
                product.type,
                product.merchantWeb?.id ?: "",
                product.merchantWeb?.merchantName ?: "",
                product.merchantWeb?.logo,
                product.merchantWeb?.subOrNot == true,
                product.affInfo?.link, product.traceId ?: ""
            )
        }
    }

    private fun setListener(activity: FragmentActivity) {
        val merchantWebVOF = product.merchantWeb
        viewBinding.ivFollow.run {
            trackData(
                page = pageDef,
                element = SpmElementDef.StoreSub,
                traceInfo = traceInfo(),
                onlyHit = true,
                params = trackMap().plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                    .plus("result" to "${if (merchantWebVOF?.subOrNot == true) "0" else "1"}")
            )
            click {
                merchantWebVOF?.let { it1 ->
                    CommonMutateManage.subscribeOrNotMerchant(
                        context,
                        merchantId = it1.id,
                        merchantName = it1.merchantName ?: "",
                        subOrNot = it1.subOrNot,
                        scope = activity.lifecycleScope,
                        refreshState = {
//                            updateFollow(!it1.subOrNot)
                        },
                        resultCallback = {
                            if (it) {
                                product?.let { it2 ->
                                    it2.merchantWeb?.let { it3 ->
                                        ApolloValSetExt.setApolloVal<ProductD.MerchantWeb>(
                                            it3,
                                            "subOrNot",
                                            it1.subOrNot.not()
                                        )
                                    }
                                }
                                viewBinding.ivFollow.trackData(
                                    page = pageDef,
                                    element = SpmElementDef.StoreSub,
                                    traceInfo = traceInfo(),
                                    onlyHit = true,
                                    params = trackMap().plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                                        .plus("result" to "${if (merchantWebVOF?.subOrNot == true) "0" else "1"}")
                                )
                                updateFollow(it1.subOrNot)
                            }
                        }
                    )
                }
            }
        }

        viewBinding.ivCollect.run {
            trackData(
                page = pageDef,
                traceInfo = traceInfo(),
                element = SpmElementDef.ProductDetailNewBodyCollection, onlyHit = true,
                params = trackMap().plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                    .plus("result" to "${if (product.collected == true) "0" else "1"}")
            )
            click {
                collect(activity, product)
            }
        }

        viewBinding.ivImgSearch.run {
            trackData(
                page = pageDef,
                traceInfo = traceInfo(),
                element = SpmElementDef.ImageRecognition,
                params = trackMap(), onlyHit = true
            )
            click {
                if (currentImgUrl?.isNotEmpty() == true && product.id?.isNotEmpty() == true) {
                    CommonRoute.toFindSimilarGoods(currentImgUrl!!, product.id!!, product.type)
                }
            }
        }

        viewBinding.llInfo.run {
            trackData(
                page = pageDef,
                traceInfo = traceInfo(),
                element = SpmElementDef.ProductDetailNewBody,
                params = trackMap(), onlyHit = true
            )
//            click {
//                if (!isSimpleDialog) {
//                    if (product?.logistics?.deliveryTime != null || product?.paymentWay?.isNotEmpty() == true) {
//                        ProductInfoDialog(
//                            context as FragmentActivity,
//                            product.logistics?.deliveryTime,
//                            product?.paymentWay as List<String>?,
//                            product.morePayFlag == true
//                        ) {
//                            toLink(product)
//                        }.show((context as FragmentActivity).supportFragmentManager, "product_info")
//                    }
//                }
//            }
        }

        viewBinding.tvBuy.toProductLink(SpmElementDef.ProductDetailNewBodyBuy)

        viewBinding.llContent.toProductLink(SpmElementDef.ProductDetailNewBody)

        if (!hasShowed) {
            viewBinding.ivStore.toStoreHome(product, needExpouse = true)
        }

        viewBinding.tvStoreName.toStoreHome(product)

        viewBinding.tvVisitStore.toStoreHome(product)
    }

    //收藏商品
    private fun collect(activity: FragmentActivity, product: ProductD) {
        product?.id?.let { it1 ->
            CommonMutateManage.collectProduct(
                ctx = context,
                id = it1,
                type = product.type,
                collected = product.collected == true,
                scope = activity.lifecycleScope,
                refreshState = {
                    updateCollect(product.collected?.not())
                },
                resultCallback = { it, collected ->
                    if (it) {
                        ApolloValSetExt.setApolloVal<ProductD>(
                            product,
                            "collected",
                            collected
                        )
                        viewBinding.ivCollect.trackData(
                            page = pageDef,
                            element = SpmElementDef.ProductDetailNewBodyCollection, onlyHit = true,
                            params = trackMap().plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                                .plus("result" to "${if (product.collected == true) "0" else "1"}")
                        )
                        updateCollect(product.collected)
                        viewBinding.addBoard.visibleOrGone(product.collected == true) {//展示add board
                            FlowCountDownTimer(time = 2).start(callBack = {
                            }, onFinish = {
                                viewBinding.addBoard.visibleOrGone(false) {

                                }
                            })
                            click {
                                WishlistAddBottomDialog.showAddListDialog(
                                    context,
                                    batchPros = arrayListOf(
                                        BatchProductArrEntry(
                                            id = product.id ?: "",
                                            type = product.type,
                                            url = product.mainImg ?: ""
                                        )
                                    )
                                )
                            }
                        }
                        // old toast
                        /*if (product.collected == true) {
                            activity.toastAddWishlist(it1)
                        }*/
                    }
                }
            )
        }
    }

    private fun updateFollow(followed: Boolean) {
        viewBinding.ivFollow.setImageResource(followed.let {
            if (it) com.starblink.android.common.R.mipmap.icon_detail_followed else com.starblink.android.common.R.mipmap.icon_detail_follow
        })
    }

    private fun updateCollect(collected: Boolean?) {
        viewBinding.ivCollect.setImageResource(collected?.let {
            if (it) collectedImg else collectImg
        } ?: collectImg)
    }


    private fun View.toStoreHome(product: ProductD, needExpouse: Boolean = false) {//跳转店铺主页
        trackData(
            page = pageDef,
            element = SpmElementDef.ELE_33032,
            params = trackMap(),
            traceInfo = traceInfo(),
            onlyHit = !needExpouse,
//            businessSuffixID = businessSuffixId("${context.hashCode()}_${product.id}")
            businessSuffixID = businessSuffixId(product)
        )
        click {
            turnWeb?.invoke()
            product.merchantWeb?.let {
                CommonRoute.startStoreDetail(context, it.id)
            }
        }
    }

    private fun View.toProductLink(
        ele: Int,
    ) {//跳转商品外链
        trackData(
            page = pageDef,
            element = ele,
            traceInfo = traceInfo(),
            params = trackMap(), onlyHit = true
        )

        click {
            product?.id?.let { it1 ->
                CommonRoute.startProductLink(
                    context,
                    product.url,
                    it1, productId = product.productId ?: "", product.standardSpuIds ?: "",
                    product.collected == true,
                    product.type,
                    product.merchantWeb?.id ?: "",
                    product.merchantWeb?.merchantName ?: "",
                    product.merchantWeb?.logo,
                    product.merchantWeb?.subOrNot == true,
                    product.affInfo?.link, product.traceId ?: ""
                )
            }
        }
    }

    private fun traceInfo() =
        if (index == 0 && firstTraceInfo?.isNotEmpty() == true) firstTraceInfo else product.traceInfo
}